namespace hjc {

	export class UIAdapater implements ILaunchable {

		private $ratio: number;					//屏幕适配比（=1时无留边，<1时左右留边，>1时上下留边）
		private $rectT: eui.Rect;				//上留边
		private $rectB: eui.Rect;				//下留边
		private $rectL: eui.Rect;				//左留边
		private $rectR: eui.Rect;				//右留边	

		public launch(options: LaunchOptions): ILaunchable {
			let stage = ui.getStage();
			stage.removeChildren();
			game.container = ui.addToStage(new eui.UILayer());
			if (!!options.configs.showAll) {
				game.container.name = '游戏主容器(全铺满)';
				ui.getStage().scaleMode = egret.StageScaleMode.SHOW_ALL;
			} else {
				game.container.name = '游戏主容器(自适配)';
				stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
				let color = options.configs.paddingColor;
				color = numeric(color) ? color : Color.BLACK;
				this.$rectT = ui.setAlign(ui.newRect({ color, name: '上留边' }), { hor: 0, top: 0 }, game.container);
				this.$rectB = ui.setAlign(ui.newRect({ color, name: '下留边' }), { hor: 0, bottom: 0 }, game.container);
				this.$rectL = ui.setAlign(ui.newRect({ color, name: '左留边' }), { ver: 0, right: 0 }, game.container);
				this.$rectR = ui.setAlign(ui.newRect({ color, name: '右留边' }), { ver: 0, left: 0 }, game.container);
				stage.addEventListener(egret.Event.RESIZE, this._onResized, this);
				this._calculate();
				this._resize();
			}
			return this;
		}

		//非showAll模式下屏幕大小变化
		private _onResized(): void {
			this._calculate();
			this._resize();
			game.manager.layer.resizeAll();
		}

		//非showAll模式下重计算屏幕比例
		private _calculate(): void {
			let [gmW, gmH] = [game.width, game.height];
			let [dvW, dvH] = [ui.getStageWidth(), ui.getStageHeight()];
			this.$ratio = gmW * dvH / gmH / dvW;
			game.scale = (this.$ratio < 1) ? this.$ratio : 1;
			game.paddingLR = 0; game.paddingTB = 0;
			if (this.$ratio < 1) game.paddingLR = Math.round((dvW - gmW * game.scale) / 2);
			else if (this.$ratio > 1) game.paddingTB = Math.round((dvH - gmH * game.scale) / 2);
		}

		//非showAll模式下重置屏幕
		private _resize(): void {
			[this.$rectT, this.$rectB, this.$rectL, this.$rectR].forEach(rect => rect.visible = false);
			this.$rectT.visible = game.paddingTB > 0;
			this.$rectB.visible = game.paddingTB > 0;
			this.$rectL.visible = game.paddingLR > 0;
			this.$rectR.visible = game.paddingLR > 0;
			if (game.paddingTB > 0) {
				this.$rectT.height = game.paddingTB;
				this.$rectB.height = game.paddingTB;
			} else if (game.paddingLR > 0) {
				this.$rectL.width = game.paddingLR;
				this.$rectR.width = game.paddingLR;
			}
		}
	}
}